import { memo, useEffect, useMemo, useState } from "react";
import { Empty, Modal, Row, Space } from "antd";
import { CheckCard } from "@ant-design/pro-components";
import { ProductType, propsType } from "../../config";
import { useFetch_commitProduct, useFetch_getProductInfo } from "../../../../service/product";
import Course_search from "../course_search";
import { useFetch_getCards } from "../../../../service/cards";
import { unionBy } from "lodash-es";
import { CreditCardOutlined } from "@ant-design/icons";
import { getCardType } from "../../../../utils";
import ProductCardtype from "./style";
import { cardType } from "../../../course/cpms/card/config";
import { sampleDataType } from "../../../../service/course";

const ProductCard = memo((props: propsType & { courses: sampleDataType[] }) => {
  const { id, open, close, courses } = props;
  const { refetch, data: cards, getLoading } = useFetch_getCards();
  const [getProductInfo, getProductInfoLoading]: [
    (id: string) => Promise<ProductType>,
    boolean
  ] = useFetch_getProductInfo() as [
    (id: string) => Promise<ProductType>,
    boolean
  ];
  const [edit] = useFetch_commitProduct();

  const [selectCards, setSelectCards] = useState<string[]>([]);
  const [showNotCardsTip, setShowNotCardsTip] = useState(true);
  const [productInfo, setProductInfo] = useState<ProductType>();

  const newCards = useMemo(() => {
    return unionBy(
      JSON.parse(productInfo?.cards ?? "[]"),
      cards,
      "id"
    ) as unknown as cardType[];
  }, [cards, productInfo?.cards]);
  useEffect(() => {
    if (JSON.parse(productInfo?.cards ?? "[]").length > 0) {
      const newSelectCards = newCards.map((item) => item.id);
      setSelectCards(newSelectCards);
    }
  }, [productInfo?.cards]);

  useEffect(() => {
    if (id) {
      void getProductInfo(id).then((res: ProductType) => {
        setProductInfo(res);
      });
    }
  }, [id]);

  const getCourseName = (id: string) => {
    return courses?.find((item) => item.id === id)?.name;
  };

  const saveCard = () => {
    const newCards: cardType[] = [];
    cards.forEach((item) => {
      if (selectCards.includes(item.id)) newCards.push(item);
    });
    JSON.parse(productInfo?.cards ?? "[]").forEach((item: cardType) => {
      if (selectCards.includes(item.id)) newCards.push(item);
    });
    edit(id, { cards: JSON.stringify(newCards) });
    close();
  };
  const onSelected = (courseId: string) => {
    setShowNotCardsTip(false);
    refetch({
      courseId
    });
  };
  return (
    <Modal
      title="绑定消费卡"
      width="55vw"
      open={open}
      onOk={() => saveCard()}
      onCancel={close as () => void}
    >
      <Row justify="end">
        <Course_search onSelected={onSelected} />
      </Row>
      <Row justify="center" style={{ padding: "15px" }}>
        {newCards.length !== 0 ? (
          <ProductCardtype>
            <CheckCard.Group
              loading={getProductInfoLoading || getLoading}
              multiple
              value={selectCards}
              onChange={(value) => setSelectCards(value as string[])}
              style={{ maxHeight: "80vh", overflowY: "auto" }}
            >
              {newCards.map((item) => {
                return (
                  <CheckCard
                    key={item.id}
                    size="small"
                    value={item.id}
                    style={{ width: "15vw" }}
                    avatar={<CreditCardOutlined />}
                    title={
                      <Row>
                        <Space style={{ fontSize: "13px" }}>
                          {getCourseName(item?.courseId)}
                          {getCardType(item?.type)}
                        </Space>
                        <div
                          style={{
                            fontSize: "15px",
                            fontWeight: "550",
                            color: "#2b98ff"
                          }}
                        >
                          {item?.name}
                        </div>
                      </Row>
                    }
                    description={
                      <Space>
                        <span>次数：{item.time}次</span>
                        <span>有效期：{item.validityDay}天</span>
                      </Space>
                    }
                  />
                );
              })}
            </CheckCard.Group>
          </ProductCardtype>
        ) : showNotCardsTip ? (
          <Empty description="">请搜索门店并绑定消费卡</Empty>
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="">
            该门店无消费卡
          </Empty>
        )}
      </Row>
    </Modal>
  );
});

export default ProductCard;
